const express = require(`express`);
const router = express.Router();
const mongoose = require("mongoose");
const _ = require("lodash");
const Log = require('../model/system/log');
router.post("/api/v1/getDataCount", async (req, res, next) => {
    try {
        // console.log("req.body", req.body);
        var Model = mongoose.model(req.body.schema);
        var datas = Model.count(req.body.query);
        var result = await datas.exec();
        res.jsonp(result);
    } catch (e) {
        console.error(e);
        res.status(501).send(e.message);
    }
});
router.post("/api/v1/getData", async (req, res, next) => {
    //
    try {
        if (_.isEmpty(req.body.schema) && typeof req.body.schema !== "string") {
            throw "请求有误，请检查条件是否正常";
        }
        // console.log("req.body", req.body);
        const Model = mongoose.model(req.body.schema);
        var datas = Model.find(req.body.query);

        if (req.body.populate)
            req.body.populate.forEach((p) => {
                datas.populate(p);
            });

        if (req.body.select) datas.select(req.body.select);
        if (req.body.skip) datas.skip(req.body.skip);

        if (req.body.limit) datas.limit(req.body.limit);

        if (req.body.sort) datas.sort(req.body.sort);
        // console.log(req.body.skip + ":" + req.body.limit);
        var result = await datas.exec();
        res.jsonp(result);
    } catch (e) {
        // console.error(e);
        res.status(501).send(e.message);
    }
    //
});

router.post("/api/v1/deleteData", async (req, res, next) => {
    try {
        if (JSON.stringify(req.body.query) == "{}" || !req.body.query) {
            throw "查询条件为空";
        }
        const Model = mongoose.model(req.body.schema);

        // 获取删除的用户信息
        const number =
            req.session && req.session.number ? req.session.number : "null";
        const removeQuery = Model.delete(req.body.query, number);

        var result = await removeQuery.exec();
        res.jsonp(result);
    } catch (e) {
        console.error(e);

        res.status(501).send(e.message);
    }
});

router.delete("/api/v1/data", async (req, res, next) => {
    try {
        if (JSON.stringify(req.body.query) == "{}" || !req.body.query) {
            throw "查询条件为空";
        }
        const Model = mongoose.model(req.body.schema);

        // 获取当前用户信息
        const number =
            req.session && req.session.number ? req.session.number : "null";
        console.log(req.body.query);
        const removeQuery = Model.deleteOne(req.body.query);
        var result = await removeQuery.exec();
        res.jsonp(result);
    } catch (e) {
        console.error(e);

        res.status(501).send(e.message);
    }
});
router.post("/api/v1/data", async (req, res, next) => {
    try {
        let results = null;
        const Model = mongoose.model(req.body.schema);
        // 获取当前用户信息
        const number =
            req.session && req.session.number ? req.session.number : "null"
        const userId =
            req.session && req.session.userId ? req.session.userId : undefined;
        let createData = req.body.data
        if (Array.isArray(createData)) {
            createData = createData.map(item => {
                // item['createBy'] = number
                item['createAt'] = new Date()
                if (userId) item['createByUserId'] = userId
                return item
            })

        } else {
            createData = {
                ...createData,
                createBy: number,
                createAt: new Date(),
            }
            if (userId) createData['createByUserId'] = userId
        }
        results = await Model.create(createData);
        res.jsonp(results);
    } catch (e) {
        console.error(e);
        res.status(501).send(e.message);
    }
});
router.put("/api/v1/data", async (req, res, next) => {
    try {
        const Model = mongoose.model(req.body.schema);

        // 获取当前用户信息
        const number =
            req.session && req.session.number ? req.session.number : "null";

        const updateQuery = Model.update(req.body.query, {
            ...req.body.update,
            updateBy: number,
            updateAt: Date.now(),
        }, {
            multi: true,
        });
        if (JSON.stringify(req.body.query) === "{}" || !req.body.query) {
            throw "查询条件为空";
        }
        if (JSON.stringify(req.body.update) === "{}" || !req.body.update) {
            throw "查询条件为空";
        }
        var result = await updateQuery.exec();
        res.jsonp(result);
    } catch (e) {
        console.error(e);
        res.status(501).send(e.message);
    }
});

router.post("/api/v1/getRow", async (req, res, next) => {
    try {
        if (_.isEmpty(req.body.schema) && typeof req.body.schema !== "string") {
            throw "请求有误，请检查条件是否正常";
        }

        const Model = mongoose.model(req.body.schema);
        var query = Model.findOne(req.body.query);

        if (req.body.populate)
            req.body.populate.forEach((p) => {
                query.populate(p);
            });

        if (req.body.select) query.select(req.body.select);

        var data = await query.exec();

        res.json({
            code: "OK",
            msg: "成功",
            data: data || {}
        });
    } catch (e) {
        res.status(501).send({
            code: "Error",
            msg: e.message,
            data: null
        });
    }
});
module.exports = router;
